/******************************************************************************************************
Copyright (C) 2019 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/
/*globals Application, File, RawToMChromReporter, RawToMChromEngine, dialog, settings, dir, File, TextStream, MessageBox, Env, Dir, date2ISOString, serialization, mainWindow*/
/*jslint plusplus: true, continue: true*/

function RawToMChromMain(aInputFile, aResFile, aLogFile) {
	"use strict";
	var startingDate, resPath, name, workingDocument, settings = {}, logText, i, engine, currentDate, finishingDate;

	function getName(aPath) {
		var first, last, name;

		first = aPath.lastIndexOf("/") + 1;
		last = aPath.length;
		name = aPath.substr(first, last);
		return name;
	}

	function writeLog(aText, aFile, aStartDate, aFinishDate) {
		var f, s;
		f = new File(aFile);
		if (f.exists) {
			f.remove();
			f = new File(aFile);
		}
		f.open(File.ReadWrite);
		s = new TextStream(f);
		s.writeln("[" + aStartDate + "] " + "RawToMChromMain: starting");
		s.writeln(aText);
		s.writeln("[" + aFinishDate + "] " + "RawToMChromMain: finishing");
		f.close();
	}

	//Working Document
	startingDate = date2ISOString(new Date()).toString().replace(new RegExp("\\:", 'g'), ".");
	logText = "\t Input: " + aInputFile + "\n";
	logText += "\t Log File: " + aLogFile + "\n";
	logText += "\t Output: " + aResFile + "\n";


	try {
		var ok = serialization.open(aInputFile);
		name = getName(aInputFile);
		logText += "\t Experiment: " + name + "\n";
		workingDocument = mainWindow.activeDocument;
	//Engine
		if (workingDocument.isValid() && ok) {
			engine = new RawToMChromEngine(aResFile);
			engine.run(aInputFile);
			currentDate = date2ISOString(new Date()).toString().replace(new RegExp("\\:", 'g'), ".");
			logText += engine.log;
			workingDocument.close();
		} else {
			logText += "RawToMChromMain: Not valid Input found " + aInputFile + "\n";
		}
	} catch (ERR) {
		logText += "RawToMChromMain: Error " + ERR + "\n";
	}

	//Log
	finishingDate = date2ISOString(new Date()).toString().replace(new RegExp("\\:", 'g'), ".");
	writeLog(logText, aLogFile, startingDate, finishingDate);
}

